<template>
  <!-- 新增编辑 -->
  <a-modal
    width="100%"
    height="100%"
    :bodyStyle="{ padding: 0 }"
    wrap-class-name="ai-rag-process-design-modal"
    :visible="props.visible"
    :footer="null"
    @update:visible="updateVisible"
    @close="updateVisible(false)"
  >
    <template #title>
      <div class="process-header-container">
        <div class="header-icon-container">
          <img :src="getImage(props.data?.icon)" />
        </div>
        <div class="header-icon-placeholder"></div>
        <div class="jeecg-modal-title-editor">
          <div class="text-area">
            <span>{{ props.data?.name }}</span>
            <span>
              <EditOutlined @click="editInfo" />
            </span>
          </div>
        </div>
        <a-space class="action-container">
          <!-- <a-badge count="5">
            <a-button>
              <template #icon><user-switch-outlined /></template>
              问题
            </a-button>
          </a-badge> -->
          <a-button @click="handleDebugClick">
            <template #icon><user-switch-outlined /></template>
            调试
          </a-button>
          <a-dropdown-button type="primary" @click="handleSaveClick">
            保存
            <template #overlay>
              <a-menu @click="handleMenuClick">
                <a-menu-item key="1">
                  <UserOutlined />
                  发布
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown-button>
        </a-space>
      </div>
    </template>
    <div
      class="container"
      :style="{
        overflow: 'hidden',
        position: 'relative'
      }"
    >
      <div class="container" ref="container"></div>
      <a-drawer
        :visible="debugVisible"
        title="调试"
        width="500px"
        :get-container="false"
        :mask="false"
        :maskClosable="false"
        :style="{ position: 'absolute' }"
        :bodyStyle="{ padding: '0 20px' }"
        :z-index="1009"
        @update:visible="handleDebugVisible"
      >
        <a-tabs>
          <a-tab-pane key="1" tab="输入">
            <a-form ref="userFormRef" :model="debugForm" :label-col="{ span: 24 }" :wrapper-col="{ span: 24 }">
              <a-form-item
                v-for="(item, index) in filteredInputParams"
                :key="index"
                :label="item.name"
                :required="item.required"
                :wrapper-col="{ span: 24 }"
                :rules="item.required ? [{ required: true, message: `请输入${item.name}` }] : []"
              >
                <a-input v-if="item.type === 'string'" v-model:value="debugForm[item.field]" placeholder="请输入文本" />
                <a-input-number v-else-if="item.type === 'number'" v-model:value="debugForm[item.field]" placeholder="请输入数字" />
                <div v-else-if="item.type === 'picture'" class="picture-upload-container">
                  <a-upload :action="uploadUrl" :show-upload-list="false" @change="info => handlePictureChange(info, index)">
                    <a-button> <a-icon type="upload" /> 上传图片 </a-button>
                  </a-upload>
                  <div v-if="item.field" class="preview-image">
                    <img :src="item.value" alt="预览图" />
                  </div>
                </div>
              </a-form-item>
            </a-form>
            <a-button style="width: 100%" type="primary" @click="handleStartDebugClick">开始调试</a-button>
          </a-tab-pane>
          <a-tab-pane key="2" tab="详情" force-render>
            <div :class="['logs-box', flowStore.status]">
              <div class="logs-bar">
                <div class="bar-item status">
                  <div class="item-title">状态</div>
                  <div class="item-content">
                    <div class="ant-space css-9m98ij ant-space-horizontal ant-space-align-center" style="gap: 8px">
                      <div class="ant-space-item" style="">
                        <span class="app-iconify anticon" style="font-size: 14px; display: inline-flex"></span>
                      </div>
                      <!---->
                      <div class="ant-space-item">
                        <span v-if="flowStore.isRunning">调试中</span>
                        <span v-if="flowStore.isFailed">调试失败</span>
                        <span v-if="flowStore.isFinished">调试成功</span>
                      </div>
                      <!---->
                    </div>
                  </div>
                </div>
                <div class="bar-item">
                  <div class="item-title">调试时间</div>
                  <div class="item-content">
                    <span>{{ flowStore.timeText }}</span>
                  </div>
                </div>
              </div>
              <div class="divider-text">参数</div>
              <div class="params-bar">
                <div class="params-item input">
                  <div class="title">输入</div>
                  <div class="content">
                    <pre>{{ flowStore.inputParams }}</pre>
                  </div>
                </div>
                <div class="params-item output">
                  <div class="title">输出</div>
                  <div class="content">
                    <pre>{{ flowStore.outputParams }}</pre>
                  </div>
                </div>
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane key="3" tab="追踪">
            <div class="logs-box">
              <div class="node-bar">
                <div
                  :class="['node-item', item.status, item.expansion ? 'expansion' : '']"
                  v-for="(item, index) in flowStore.nodeSteps"
                  :key="index"
                  @click="handleDebugNode(item)"
                >
                  <div class="node-header">
                    <div class="ant-space css-9m98ij ant-space-horizontal ant-space-align-center info" style="gap: 8px">
                      <div class="ant-space-item" style="">
                        <div class="icon">
                          <img style="width: 20px; height: 20px" :src="getImggeUrl(item.node.type)" alt="" />
                        </div>
                      </div>
                      <div class="ant-space-item">
                        <span class="airag-node-label">{{ item.node.text }}</span>
                      </div>
                    </div>
                    <div class="time">
                      <span>耗时：{{ item.timeText }}</span>
                    </div>
                  </div>
                  <div class="params-bar">
                    <div class="params-item input">
                      <div class="title">输入</div>
                      <div class="content">
                        <pre>{{ item.inputParams }}</pre>
                      </div>
                    </div>
                    <div class="params-item output">
                      <div class="title">输出</div>
                      <div class="content">
                        <pre>{{ item.outputParams }}</pre>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </a-tab-pane>
          <a-tab-pane key="4" tab="结果">
            <div class="logs-box finished">
              <div class="params-bar">
                <div class="params-item output">
                  <div class="content">
                    <pre>{{ flowOutputParams }}</pre>
                  </div>
                </div>
              </div>
            </div>
          </a-tab-pane>
        </a-tabs>
      </a-drawer>
      <property-dialog
        v-model:visible="settingVisible"
        :title="title"
        :nodeData="nodeData"
        :flowDetail="flowDetail"
        :lf="lf"
        @closed="showAttribute = false"
      />
    </div>

    <FlowAddEditInfo v-model:visible="showEditInfo" v-if="showEditInfo" :isUpdate="isUpdateInfo" :data="current" @done="done" />
  </a-modal>
</template>

<script setup>
import { ref, onMounted, computed, reactive, onUnmounted, watch } from 'vue';
import { message } from 'ant-design-vue';
import LogicFlow from '@logicflow/core';
import { Control, Menu, DndPanel } from '@logicflow/extension';
import '@logicflow/core/dist/index.css';
import '@logicflow/extension/lib/style/index.css';
import { generateUniqueId, getNodeWidth, getNodeHeight, buildUUID } from '@/utils/common/index.js';
import { register } from '@logicflow/vue-node-registry';
import customEdge from './edges/custom-line/index.js';
import start from './registernode/start/start.js';
import end from './registernode/end/end.js';
import classifier from './registernode/classifier/classifier.js';
import llm from './registernode/llm/llm.js';
import knowledge from './registernode/knowledge/knowledge.js';
import reply from './registernode/reply/reply.js';
import switchNode from './registernode/switch/switch.js';

import codeNode from './registernode/code/code.js';

import enhanceJavaNode from './registernode/enhanceJava/enhanceJava.js';
import httpNode from './registernode/http/http.js';
import dbQueryNode from './registernode/dbQuery/dbQuery.js';

import { ContextPad } from './plugins/context-pad/index.js';
import PropertyDialog from './PropertySetting/PropertyDialog.vue';
import { Parser as Zt } from '../../utils/logic2LiteFlow.js';
// import { collectUpstreamNodes } from '../../utils/flowNodeUtils';
// import LLMStreamClient from '@/views/super/airag/utils/LLMStreamClient.js';
import LLMStreamClient from '@/utils/request/request-util';
import { useFlowRunStore } from '@/store/modules/airagFlowRunStore';
import { FlowApi } from '@/views/super/airag/aiflow/api/FlowApi';
import FlowAddEditInfo from './flow-add-edit-info.vue';
import { API_BASE_PREFIX } from '@/config/setting';
import { getToken } from '@/utils/token-util';
import defaultImg from '../img/ailogo.png';
const flowStore = useFlowRunStore();
const props = defineProps({
  visible: Boolean,
  data: Object
});
const userFormRef = ref(null);
const labelCol = { style: { width: '110px' } };
const debugForm = ref({});
const filteredInputParams = ref([]);
const debugInputParams = computed(() => {
  if (!startNode.value || !startNode.value.properties || !Array.isArray(startNode.value.properties.inputParams)) {
    return [];
  }
  return startNode.value.properties.inputParams.filter(item => item.type !== 'string[]');
});
const isUpdateInfo = ref(false);
const loading = ref(false);
const current = ref({});
const emits = defineEmits(['update:visible', 'done']);
const showEditInfo = ref(false);
const container = ref(null);

// 是否是编辑状态
const isUpdate = ref(false);

const debugVisible = ref(false);
const isDebugging = ref(false);
const startNode = ref();
// 表单数据

const showAttribute = ref(false);
let nodeData = ref(null);
const lf = ref(null);
const settingVisible = ref(false);
let config = reactive({
  background: {
    backgroundColor: '#f7f9ff'
  },
  grid: {
    size: 10,
    visible: true
  },
  keyboard: {
    enabled: true
  },
  edgeTextDraggable: true,
  hoverOutline: true
});
const flowDetail = computed(() => {
  return {
    id: props.data ? props.data.id : '',
    createBy: props.data ? props.data.createBy : '',
    createTime: props.data ? props.data.createTime : '',
    updateBy: props.data ? props.data.updateBy : '',
    updateTime: props.data ? props.data.updateTime : '',
    applicationName: props.data ? props.data.applicationName : '',
    name: props.data ? props.data.name : '',
    descr: props.data ? props.data.descr : '',
    icon: props.data ? props.data.icon : '',
    chain: props.data ? props.data.chain : '',
    design: props.data ? JSON.parse(props.data.design) : {},
    status: props.data ? props.data.status : 'enable',
    metadata: props.data ? props.data.description : ''
  };
});
const editInfo = () => {
  isUpdateInfo.value = true;
  showEditInfo.value = true;
};
const done = value => {
  if (value === 'ok') {
    showEditInfo.value = false;
  }
};
onMounted(async () => {
  if (props.data) {
    current.value = props.data;
    lf.value = new LogicFlow({
      nodeTextEdit: false,
      edgeTextEdit: false,
      textEdit: false,
      grid: true,
      adjustEdge: false, // 允许调整边
      adjustEdgeStartAndEnd: false, // 是否允许拖动边的端点来调整连线
      adjustNodePosition: true, // 是否允许拖动节点
      edgeSelectedOutline: true, // 边被选中时是否显示边的外框
      nodeSelectedOutline: true, // 节点被选中时是否显示节点的外框
      hoverOutline: true, // 鼠标hover节点时是否显示节点的外框
      background: {
        backgroundColor: '#f0f2f5'
      },
      keyboard: {
        enabled: true
      },
      container: container.value,
      plugins: [ContextPad, Control]
    });

    // LogicFlow.user(Control);
    // 注册自定义节点
    // lf.value.register(start);
    register(customEdge, lf.value);
    lf.value.setDefaultEdgeType('base-edge');
    register(start, lf.value);
    register(end, lf.value);
    register(classifier, lf.value);
    register(llm, lf.value);
    register(knowledge, lf.value);
    register(reply, lf.value);
    register(switchNode, lf.value);
    register(codeNode, lf.value);
    register(enhanceJavaNode, lf.value);
    register(httpNode, lf.value);
    register(dbQueryNode, lf.value);
    // lf.value.setTheme({
    //   outline: {
    //     fill: 'transparent',
    //     stroke: '#949494',
    //     strokeDasharray: '3,3',
    //     hover: {
    //       stroke: '#949494'
    //     }
    //   }
    // });

    // lf.value.render(JSON.parse( props.data.design));
    lf.value.on('node:click', ({ data }) => {
      // console.log('节点点击事件', data);
      // // 这里可以处理节点点击事件
      // //  data.properties.yrh="adfas"+ Math.random();
      // //  var data1=  lf.value.getNodeModelById("1");
      // //      var data2=  lf.value.getNodeModelById("2");
      // //  debugger;
      // //  console.log('data1', data1);
      // // lf.value.getNodeModelById(data.id).setProperties({yrh:"xxxx"+ Math.random()});
      // var data1 = lf.value.getNodeModelById('1');
      // data1.isHovered = !data1.isHovered;
      // data1.isSelected = true;
      // console.log('12312' + data1.isHovered);
      // 这里可以更新节点的属性
      // data.properties.yrh = "更新后的值";
      // lf.value.updateNode(data);
    });
    lf.value.on('node:dbclick', ({ data }) => {
      nodeData.value = data;
      console.log('节点双击事件', data);
      // collectUpstreamNodes(data,lf.value.graphModel);

      if (['start', 'end', 'classifier', 'llm', 'knowledge', 'reply', 'switch', 'code', 'enhanceJava','http','dbquery'].includes(data.type)) {
        settingVisible.value = true;
      }
    });
    lf.value.on('custom:addNode', ({ data, model, anchorData }) => {
      onCustomAddNode(data, model, anchorData);
    });

    lf.value.render(JSON.parse(props.data.design));
    isUpdate.value = true;
  } else {
    isUpdate.value = false;
  }
});

onUnmounted(() => {
  flowStore.$reset();
});

watch(
  () => flowStore.status, // 需要监听的状态
  (newVal, oldVal) => {
    console.log('status 变化:', oldVal, '→', newVal);
    // if (newVal === 'running') {
    //   lf.value.updateEditConfig({
    //     adjustNodePosition: false
    //   });
    // }

    // lf.value.updateEditConfig({
    //   adjustNodePosition: true
    // });

    // const edges = lf.value.getGraphData().edges;
    // edges.forEach(edge => {
    //   if (edge.type === 'base-edge') {
    //     // 设置边的运行状态
    //     var tempEdge = lf.value.getEdgeModelById(edge.id);
    //     tempEdge.setProperties({
    //       runStatus: newVal
    //     });
    //     tempEdge.closeEdgeAnimation();
    //   }
    // });
  },
  { deep: true } // 深度监听（对象/数组时需启用）
);

const buildAnchorNextIdsMap = () => {
  // 这里实现具体的锚点映射逻辑
  const map = new Map();

  // 示例：处理SWITCH节点的锚点关系
  lf.value.getGraphData().nodes.forEach(node => {
    if (node.type === 'SWITCH') {
      // 假设每个SWITCH节点有3个锚点
      const anchors = ['case1', 'case2', 'default'];
      anchors.forEach((anchor, index) => {
        const anchorId = `${node.id}-${anchor}`;
        // 获取该锚点连接的下游节点ID
        const nextIds = this.getConnectedNodes(node.id, anchor);
        map.set(anchorId, nextIds);
      });
    }
  });

  return map;
};
const getSwitchBranches = node => {
  return [
    { type: 'IF', label: '条件为真' },
    { type: 'ELSE', label: '条件为假' }
  ];
};
// 获取分类节点分支
const getClassifierBranches = node => {
  const { options } = node.properties;
  return options.categories
    .map(category => ({
      type: 'CATEGORY',
      label: category.label
    }))
    .concat({ type: 'ELSE', label: '其他' });
};
// 获取分类节点锚点ID
const getClassifierAnchorId = (nodeId, type, index) => {
  return `${nodeId}_classifier_${index}`;
  //  return `${nodeId}-anchor_right`;
  // return `${nodeId}_classifier_${type}_${index}`;
};
const getSwitchAnchorId = (nodeId, type, index) => {
  return `${nodeId}_switch_${index}`;
  //  return `${nodeId}-anchor_right`;
  // return `${nodeId}_classifier_${type}_${index}`;
};

const findConnectedNodes = (anchorId, edges) => {
  return edges.filter(edge => edge.sourceAnchorId === anchorId).map(edge => edge.targetNodeId);
};
const nodeConnections = new Map();
// 验证工作流数据
const validateWorkflowData = () => {
  const flowData = lf.value.getGraphRawData();
  if (!flowData) throw new Error('尚未初始化');

  const { nodes, edges } = flowData;
  if (nodes.length === 0) throw new Error('请添加节点');

  //TODO:报错时清除状态,下一步修改成和节点类似，从存储中获取状态。
  edges.forEach(edge => {
    delete edge.properties.runStatus;
  });

  const requiredNodeTypes = ['end', 'switch', 'classifier'];
  const nodeTypeMap = new Map();

  // 检查必要节点
  nodes.forEach(node => {
    if (requiredNodeTypes.includes(node.type)) {
      let typeNodes = nodeTypeMap.get(node.type);
      if (!typeNodes) typeNodes = [];
      typeNodes.push(node);
      nodeTypeMap.set(node.type, typeNodes);
    }
  });

  if (!nodeTypeMap.has('end')) {
    message.error('请添加结束节点');
    return;
  }

  // 检查开关节点
  const switchNodes = nodeTypeMap.get('switch');
  if (switchNodes && switchNodes.length > 0) {
    switchNodes.forEach(switchNode => {
      const { text, options } = switchNode.properties;
      if (!options || !Array.isArray(options.if) || options.if.length === 0) {
        // throw new Error(`${text} 节点的“IF”分支条件不能为空`);
        message.error(`${text} 节点的“IF”分支条件不能为空`);
        throw new Error(`${text} 节点的“IF”分支条件不能为空`);
      }

      const branches = getSwitchBranches(switchNode);
      branches.forEach((branch, index) => {
        var anchorId = '';
        if (branch.type === 'ELSE') {
          anchorId = getSwitchAnchorId(switchNode.id, branch.type, 'else');
        } else {
          anchorId = getSwitchAnchorId(switchNode.id, branch.type, index + 1);
        }

        const connectedNodes = findConnectedNodes(anchorId, edges);

        if (connectedNodes.length === 0) {
          message.error(`${text} 节点的“${branch.label}”分支未连接下一个节点`);
          throw new Error(`${text} 节点的“${branch.label}”分支未连接下一个节点`);
        }

        if (branch.type === 'ELSE') {
          options.else.next = connectedNodes[0];
        } else {
          options.if[index].next = connectedNodes[0];
        }
        nodeConnections.set(anchorId, connectedNodes);
      });
    });
  }
  // 检查分类节点
  const classifierNodes = nodeTypeMap.get('classifier');
  if (classifierNodes && classifierNodes.length > 0) {
    classifierNodes.forEach(classifierNode => {
      const { text, options } = classifierNode.properties;
      if (!options || !Array.isArray(options.categories) || options.categories.length === 0) {
        message.error(`${text} 节点的分类不能为空`);
        throw new Error(`${text} 节点的分类不能为空`);
      }

      const branches = getClassifierBranches(classifierNode);
      branches.forEach((branch, index) => {
        var anchorId = '';
        if (branch.type === 'ELSE') {
          anchorId = getClassifierAnchorId(classifierNode.id, branch.type, 'else');
        } else {
          anchorId = getClassifierAnchorId(classifierNode.id, branch.type, index + 1);
        }

        const connectedNodes = findConnectedNodes(anchorId, edges);

        if (connectedNodes.length === 0) {
          message.error(`${text} 节点的“${branch.label}”未连接下一个节点`);
          throw new Error(`${text} 节点的“${branch.label}”未连接下一个节点`);
        }

        if (branch.type === 'ELSE') {
          options.else.next = connectedNodes[0];
        } else {
          options.categories[index].next = connectedNodes[0];
        }
        nodeConnections.set(anchorId, connectedNodes);
      });
    });
  }
  return flowData;
};
//清楚状态
const clearRunStatus = () => {
  // 清除所有节点和边的运行状态
  lf.value.graphModel.nodes.forEach(node => {
    node.setProperties({ runStatus: '' });
  });
  lf.value.graphModel.edges.forEach(edge => {
    edge.setProperties({ runStatus: '' });
    edge.closeEdgeAnimation();
  });
};
// 自定义添加节点
const onCustomAddNode = (data, model, anchorData) => {
  data.id = generateUniqueId(data.type);
  // data.nodeSortKey = data.id.substring(0, 8) + data.id.substring(data.id.length - 8)
  data.width = getNodeWidth(data);
  data.height = getNodeHeight(data);
  data.properties.width = data.width;
  data.properties.height = data.height;
  // data.properties.nodeSortKey = data.nodeSortKey

  if (anchorData) {
    data.x = anchorData.x + data.width / 2;
    data.y = anchorData.y;
  } else {
    const { transformModel } = lf.value.graphModel;
    const point = transformModel.HtmlPointToCanvasPoint([lf.value.graphModel.width / 2, lf.value.graphModel.height / 2]);

    data.x = point[0];
    data.y = point[1];
  }
  // 情况选中状态
  let zIndex = 0;
  lf.value.graphModel.nodes.forEach(node => {
    if (node.zIndex > zIndex) {
      zIndex = node.zIndex;
    }
  });

  zIndex = zIndex + 1;
  let node = lf.value.addNode(data);
  if (anchorData) {
    lf.value.graphModel.addEdge({
      type: 'base-edge',
      sourceNodeId: model.id,
      targetNodeId: node.id,
      sourceAnchorId: anchorData.id,
      startPoint: {
        x: anchorData.x,
        y: anchorData.y
      }
    });
  }
  node.setZIndex(zIndex);
  lf.value.graphModel.clearSelectElements();
  node.setSelected(true);
};
const handleSaveClick = () => {
  const flowData = validateWorkflowData();
  const anchorMap = new Map();

  // 保存
  const rawData = flowData;
  const parser = new Zt(rawData, anchorMap);
  // 3. 执行解析
  const elNodeTree = parser.parse();
  // 4. 获取EL表达式字符串
  var elResult = elNodeTree.getElString();
  props.data.design = JSON.stringify(rawData);
  props.data.chain = elResult;
  if (props.data?.id) {
    FlowApi.designSave(props.data)
      .then(async result => {
        loading.value = false;
        message.success(result.message);
      })
      .catch(() => {
        loading.value = false;
      });
  } else {
    FlowApi.add(props.data)
      .then(async result => {
        loading.value = false;
        props.data.id = result.data;
        message.success(result.message);
      })
      .catch(() => {
        loading.value = false;
      });
  }
};
const setNodeEdgeRunStatus = data => {
  var runStatus = '';
  if (data.event === 'NODE_STARTED') {
    runStatus = 'running';
  } else if (data.event === 'NODE_FINISHED') {
    if (data.data.success) {
      runStatus = 'success';
    } else {
      runStatus = 'fail';
    }
  }
  var edges = lf.value.getNodeIncomingEdge(data.data.id);
  if (!edges || edges.length === 0) {
    return;
  }

  edges.forEach(edge => {
    if (edge.type === 'base-edge') {
      // 设置边的运行状态
      edge.setProperties({
        runStatus: runStatus
      });
      edge.openEdgeAnimation();
      // if (runStatus !== 'waiting') {
      //   // const x=flowStore.getStep(edge.sourceNodeId);
      //   // if( x && x.status === 'sucess') {

      //   // }
      //   edge.openEdgeAnimation();
      // } else {
      //   edge.closeEdgeAnimation();
      // }
    }
  });
};
const handleDebugNode = item => {
  item.expansion = !item.expansion;
};
const handleDebugClick = () => {
  settingVisible.value = false;
  debugVisible.value = true;
  startNode.value = lf.value.getNodeModelById('start-node');
  if (!startNode.value || !startNode.value.properties || !Array.isArray(startNode.value.properties.inputParams)) {
    filteredInputParams.value = [];
  } else {
    filteredInputParams.value = startNode.value.properties.inputParams.filter(item => item.type !== 'string[]');
  }
};
const handleStartDebugClick = () => {
  userFormRef.value.validate().then(async valid => {
    if (valid) {
      clearRunStatus();
      flowDebug();
    }
  });
};

const flowOutputParams = computed(() => {
  const output = typeof flowStore.outputParams === 'string' ? flowStore.outputParams : JSON.stringify(flowStore.outputParams, null, 2);
  return output;
});

const flowDebug = () => {
  isDebugging.value = true;
  if (lf.value) {
    lf.value.updateEditConfig({ isSilentMode: true });
  }
  const anchorMap = new Map();
  // 保存
  const rawData = lf.value.getGraphRawData();
  const parser = new Zt(rawData, anchorMap);
  // 3. 执行解析
  const elNodeTree = parser.parse();
  // 4. 获取EL表达式字符串
  var elResult = elNodeTree.getElString();
  props.data.design = JSON.stringify(rawData);
  props.data.chain = elResult;
  var data = {
    flow: {
      design: JSON.stringify(rawData),
      chain: elResult
    },
    inputParams: debugForm.value,
    responseMode: 'streaming'
  };

  const client = new LLMStreamClient();
  const that = this;
  let abortController = client.streamChat({
    path: '/airag/flow/debug',
    data: data,
    onFlowStarted: data => {
      flowStore.$reset();
      flowStore.start(data.data.inputs);
      console.log('流程开始111', data);
    },
    onFlowFinished: data => {
      flowStore.finish(data.data.success, data.data.message, data.data.outputs);
      isDebugging.value = false;
      console.log('流程结束', data);
    },
    onNodeStarted: data => {
      console.log('节点开始', data);
      flowStore.addStep({
        node: { id: data.data.id, type: data.data.type, text: data.data.text },
        status: 'running',
        inputParams: data.data.inputs,
        outputParams: data.data.outputs
      });
      setNodeEdgeRunStatus(data);
    },
    onNodeFinished: data => {
      flowStore.updateStepStatus(data.data.id, data.data.success ? 'success' : 'fail', data.data.outputs);
      setNodeEdgeRunStatus(data);
    },
    onEnd: () => {
      console.log('流结束');
    },
    onError: err => {
      console.error('出错:', err);
    }
  });
};
const handleDebugVisible = value => {
  if (isDebugging.value == true) {
    message.warning('正在调试请稍后……');
    return;
  }
  debugVisible.value = false;
  clearRunStatus();
  endDebugging();
};
const endDebugging = () => {
  flowStore.end();
  if (lf.value) {
    lf.value.updateEditConfig({ isSilentMode: false });
  }
  isDebugging.value = false;
};

// 更改弹框状态
const updateVisible = value => {
  emits('update:visible', value);
};
const getImggeUrl = name => {
  let url = new URL(`../../../../../assets/svg/${name}-node.svg`, import.meta.url);
  return url.href;
};

// 图标上传预览地址
const icon = reactive({
  filePreviewUrl: `${API_BASE_PREFIX}/sysFileInfo/public/preview?fileId=`,
  // 上传文件时候要带header
  headers: {
    Authorization: getToken()
  }
});

/**
 * 获取图片
 * @param fileId
 */
function getImage(fileId) {
  return fileId ? icon.filePreviewUrl + fileId : defaultImg;
}
</script>

<style lang="less">
.container {
  width: 100%;
  height: 100%;
}
.ai-rag-process-design-modal {
  .ant-modal {
    max-width: 100%;
    top: 0;
    padding-bottom: 0;
    margin: 0;
  }
  .ant-modal-content {
    display: flex;
    flex-direction: column;
    height: calc(100vh);
  }
  .ant-modal-body {
    flex: 1;
  }
}

.ai-rag-process-design-modal .process-header-container {
  display: flex;
  position: relative;
}

.ai-rag-process-design-modal .process-header-container .header-icon-container,
.ai-rag-process-design-modal .process-header-container .header-icon-placeholder {
  width: 24px;
  margin-right: 4px;
}

.ai-rag-process-design-modal .process-header-container .header-icon-container {
  height: 18px;
  width: auto;
  max-width: 24px;
  position: absolute;
  left: 5px;
  z-index: 2020;
}

.ai-rag-process-design-modal .process-header-container .header-icon-container img {
  width: 100%;
  height: 100%;
}

.ai-rag-process-design-modal .process-header-container > .action-container {
  position: absolute;
  right: 46px;
  top: -6px;
  z-index: 2020;
}

.full-modal {
}

/* 自定义锚点样式 */
.custom-anchor {
  cursor: pointer;

  .custom-anchor-arrow,
  .custom-anchor-plus {
    display: none;
  }
}
.custom-anchor.anchor-selected {
  .custom-anchor-arrow {
    display: block;
  }
}
.custom-anchor.anchor-not-selected.custom-anchor-right:hover {
  .custom-anchor-plus {
    display: block !important;
  }
}

.custom-anchor .anchor-hide {
  display: none !important;
}

// .ant-modal-body {
//   padding: 1px;
// }
// .ant-drawer-body{
//   padding: 0 20px ;
// }

.gen-prompt-btn:hover {
  opacity: 0.8;
}

.logs-box .logs-bar {
  width: 100%;
  background-color: #f0f0fa;
  border-radius: 12px;
  display: flex;
  padding: 18px;
}

.logs-box .logs-bar .bar-item {
  width: 180px;
  height: 50px;
}

.logs-box .logs-bar .bar-item .item-title {
  font-size: 12px;
  color: #999;
  margin-bottom: 10px;
}

.logs-box .logs-bar .bar-item .item-content {
  font-size: 14px;
  color: #333;
  font-weight: 700;
}

.logs-box .logs-bar .bar-item.status .item-content {
  color: #67b7ff;
}

.logs-box .divider-text {
  color: #999;
  font-size: 14px;
  margin: 12px 0;
}

.logs-box .params-bar .params-item {
  width: 100%;
  border-radius: 12px;
  background-color: #f5f5f5;
  padding: 12px;
  margin-bottom: 12px;
}

.logs-box .params-bar .params-item .title {
  font-size: 12px;
  color: #999;
  margin-bottom: 4px;
}

.logs-box .params-bar .params-item .content {
  font-size: 12px;
  color: #333;
  font-weight: 700;
}

.logs-box .params-bar .params-item .content pre {
  margin-top: 0;
  margin-bottom: 0;
  white-space: pre-wrap;
  word-break: break-all;
}

.logs-box .node-bar .node-item {
  width: 100%;
  border-radius: 12px;
  background-color: #fff;
  border: 1px solid #67b7ff;
  padding: 12px;
  margin-bottom: 12px;
  cursor: pointer;
  box-shadow: 0 2px 4px #e6e6e6;
}

.logs-box .node-bar .node-item:hover {
  box-shadow: 0 4px 8px #e6e6e6;
}

.logs-box .node-bar .node-item.success {
  border-color: #4caf50;
}

.logs-box .node-bar .node-item.fail {
  border-color: #f44336;
}

.logs-box .node-bar .node-item .node-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.logs-box .node-bar .node-item .node-header .info .icon {
  transform: scale(0.8);
}

.logs-box .node-bar .node-item .node-header .info .airag-node-label {
  font-size: 14px;
}

.logs-box .node-bar .node-item .node-header .time {
  font-size: 12px;
  color: #999;
}

.logs-box .node-bar .node-item .params-bar {
  display: none;
}

.logs-box .node-bar .node-item.expansion .node-header {
  margin-bottom: 8px;
}

.logs-box .node-bar .node-item.expansion .params-bar {
  display: block;
}

.logs-box.finished .logs-bar {
  background-color: #f0fae6;
}

.logs-box.finished .logs-bar .bar-item.status .item-content {
  color: #4caf50;
}

.logs-box.failed .logs-bar {
  background-color: #fae6e6;
}

.logs-box.failed .logs-bar .bar-item.status .item-content {
  color: #f44336;
}
.lf-control {
  position: absolute; /* 或者 fixed */
  right: auto !important; /* 重置右侧约束 */
  top: auto; /* 重置顶部约束 */
  bottom: 0; /* 贴紧底部 */
  left: 0; /* 贴紧左侧 */
}
</style>